package Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;

@WebFilter(
        urlPatterns = "/*",
        initParams = {
                @WebInitParam(name = "characterEncoding", value = "utf-8")
        }
)
public class CharacterEncodingFilter implements Filter {
    private String characterEncoding;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            System.setOut(new PrintStream(System.out,true,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        System.out.println("初始化过滤器");
        this.characterEncoding = filterConfig.getInitParameter("characterEncoding");
        System.out.println("characterEncoding:"+characterEncoding);
    }
    @Override
    public void destroy() {
        System.out.println("销毁过滤器");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器操作");
        servletRequest.setCharacterEncoding(characterEncoding);
        servletResponse.setCharacterEncoding(characterEncoding);
        //让过滤器链中的其他过滤器执行，这行代码必不可少，否则，无法进入后面的Servlet执行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
